<?php
namespace App\GraphQL\Mutations\DeviceOrder;

use App\Models\DeviceOrder;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Models\Group;
use App\Models\AgentStatistical;
use Illuminate\Support\Facades\DB;
use App\Models\GlobalStatistical;

class Create
{

    /**
     * Return a value for the field.
     *
     * @param null $rootValue
     *            Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param mixed[] $args
     *            The arguments that were passed into the field.
     * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context
     *            Arbitrary data that is shared between all fields of a single query.
     * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo
     *            Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        DB::transaction(function () use ($args) {
            $data = $args['input'];
            $this->validate($data);
            $authUser = auth()->user();
            $data['user_id'] = $authUser->id;
            $data['status'] = 'WAIT_PAY';
            $deviceOrder = DeviceOrder::create($data);
            // 更新代理商订单统计
            $agentStatistical = AgentStatistical::firstOrCreate([
                'user_id' => $deviceOrder->device_group->user_id
            ]);
            $agentStatistical->increment('order_count');
            $globalStatistical = GlobalStatistical::first();
            if(!$globalStatistical){
                $globalStatistical =  GlobalStatistical::create();
            }
            $globalStatistical->increment('device_order_count');
        });
        return [
            'status' => '200',
            'message' => '创建成功'
        ];
    }

    public function validate($data)
    {
        $rules = [
            'quantity' => [
                'required',
                'integer',
                'min:1'
            ],
            'style' => [
                'required',
                Rule::in([
                    'TEA_HOUSE',
                    'INTERNET_CAFE'
                ])
            ],
            'device_group_id' => [
                'required',
                'numeric'
            ],
            'shipping_address' => [
                'required'
            ],
            'shipping_address_detail' => [
                'required'
            ],
            'receiver' => [
                'required'
            ],
            'receiving_call' => [
                'required'
            ]
        ];
        $messages = [
            'quantity.required' => '数量不能为空',
            'quantity.integer' => '数量为整数',
            'style.required' => '款式不能为空',
            'device_group_id.required' => '设备分组不能为空',
            'shipping_address.required' => '收货地址不能为空',
            'shipping_address_detail.required' => '收货详细地址不能为空',
            'receiver.required' => '收货人不能为空',
            'receiving_call.required' => '收货电话不能为空',
            'quantity.min' => '数量不能小于1',
            'device_group_id.numeric' => '设备分组为ID',
            'style.in' => '款式不能超出限制'
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        $group = Group::find($data['device_group_id']);
        if (! $group) {
            throw new \Exception('设备组不存在');
        }
        if ($group->cate !== 'DEVICE') {
            throw new \Exception('设备组类型不正确!');
        }
        return true;
    }
}
